<script setup>
import {ref, onMounted, watch} from 'vue'
import { RequestGetUserInfo, RequestUpdateUserInfo } from '@/api/Account.js'
import {RequestRiskeFileUpload} from "@/api/FileUpload.js"
import { ElMessage, ElMessageBox } from 'element-plus'
import { Upload } from '@element-plus/icons-vue'

// 用户信息（初始化为空）
const userInfo = ref({
  id: null,
  username: '',
  nickname: '',
  gender: null,
  phone: '',
  email: '',
  avatar: '',
  role: null,
  status: null,
  createdTime: ''
})

// 性别选项
const genderSelected = ref(userInfo.value.gender)
const genderOptions = [
  { label: '男', value: 1 },
  { label: '女', value: 0 },
]
watch(()=>genderSelected.value,(newVal)=>{
  genderSelected.value = newVal;
})


// 角色映射
const roleMap = {
  1: '普通用户',
  2: '管理员',
  3: '超级管理员'
}

// 状态映射
const statusMap = {
  0: '禁用',
  1: '正常'
}

// 表单验证规则
const rules = {
  nickname: [{ required: false, message: '请输入昵称', trigger: 'blur' }],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  email: [
    { pattern: /^\S+@\S+\.\S+$/, message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 模拟获取用户信息
async function fetchUserInfo() {
  try {
    const res = await RequestGetUserInfo()
    if(res.data.code === 200){
      userInfo.value = { ...res.data.data }
      genderSelected.value = userInfo.value.gender;
    }
  } catch (e) {
    ElMessage.error('获取用户信息失败')
  }
}

// 头像上传
const avatar = ref([]);
// 上传文件
async function handleChange(file) {
  console.log("上传文件", file.raw)
  try {
    const res = await RequestRiskeFileUpload(file.raw);
    // avatar[0].value = [res.data.data];
    userInfo.value.avatar = res.data.data;
    console.log("上传成功", res.data.data);
  } catch (e) {
    console.log("上传文件失败", e)
  }
}

// 保存表单
const saveForm = async () => {
  try {
    await ElMessageBox.confirm('确认保存用户信息？', '提示', {
      type: 'warning',
      confirmButtonText: '确定',
      cancelButtonText: '取消'
    })

    // 调用更新接口（假设存在）
    const res = await RequestUpdateUserInfo(userInfo.value)
    console.log("更新用户信息",res);
    ElMessage.success('保存成功！')
    // 可在此跳转回详情页：router.push('/user/profile')
  } catch (e) {
    if (e !== 'cancel') {
      ElMessage.error('保存失败')
    }
  }
}

onMounted(() => {
  fetchUserInfo()
})
</script>

<template>
  <div class="user-edit-container">
    <el-card shadow="hover" style="max-width: 600px; margin: 40px auto; border-radius: 12px">
      <template #header>
        <h3 style="margin: 0; color: #303133">编辑用户信息</h3>
      </template>

      <el-form :model="userInfo" :rules="rules" label-width="90px" size="default" status-icon>
        <!-- 昵称 -->
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="userInfo.nickname" placeholder="请输入昵称" />
        </el-form-item>

        <!-- 性别 -->
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="userInfo.gender">
            <el-radio
                v-for="option in genderOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
            >
              {{ option.label }}

            </el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 手机号 -->
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="userInfo.phone" placeholder="请输入手机号" />
        </el-form-item>

        <!-- 邮箱 -->
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userInfo.email" placeholder="请输入邮箱" />
        </el-form-item>

        <!-- 头像上传 -->
        <el-form-item label="头像">
          <div class="avatar-upload">
            <el-avatar
                :size="60"
                :src="userInfo.avatar || 'https://cube.elemecdn.com/e/fd/0fc7d20532fdaf769a25683617711png.png'"
            />
            <el-upload
                :auto-upload="false"
                :show-file-list="false"
                class="avatar-uploader"
                @change="handleChange"
            >
              <el-button type="primary" :icon="Upload" size="small" style="margin-left: 10px">
                上传头像
              </el-button>
            </el-upload>
          </div>
        </el-form-item>

        <!-- 只读信息 -->
        <el-form-item label="用户名">
          <span class="form-text">{{ userInfo.username }}</span>
        </el-form-item>

        <el-form-item label="角色">
          <span class="form-text">{{ roleMap[userInfo.role] || '未知角色' }}</span>
        </el-form-item>

        <el-form-item label="状态">
          <span class="form-text">{{ statusMap[userInfo.status] }}</span>
        </el-form-item>

        <el-form-item label="注册时间">
          <span class="form-text">{{ userInfo.createdTime?.split('T')[0] || '——' }}</span>
        </el-form-item>
      </el-form>

      <el-button type="primary" @click="saveForm" style="width: 100%">
        保 存
      </el-button>

    </el-card>
  </div>
</template>

<style scoped>
.user-edit-container {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding: 20px 0;
}

.form-text {
  color: #606266;
  font-size: 14px;
}

.avatar-upload {
  display: flex;
  align-items: center;
}

/* 头像默认样式 */
:deep(.el-avatar) {
  background-color: #909399;
}
</style>
